import React, { useState, useRef} from 'react'
import { ImageUploader, Button, Space } from 'antd-mobile'


// 新增工具函数：实际文件上传方法
export async function realUpload(file) {
  // 1. 创建表单数据
  const formData = new FormData()
  formData.append('avatar', file)
  
  // 2. 调用后端接口
  try {
    const response = await fetch('/api/api/auth/update-avatar', {
      method: 'POST',
      body: formData,
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })

    if (!response.ok) {
      throw new Error(`上传失败: ${response.statusText}`)
    }

    const data = await response.json()
    
    // 3. 返回标准格式
    return {
      url: data.avatar_url,  // 根据实际接口字段调整
      status: 'done',
      name: file.name,
      uid: Date.now().toString()
    }
  } catch (error) {
    // 4. 错误处理
    console.error('上传出错:', error)
    return {
      status: 'fail',
      message: error.message
    }
  }
}

// 修改组件使用
export default function AvatarUpload() {
  const [fileList, setFileList] = useState([])
  const [uploading, setUploading] = useState(false)
  const input = useRef(null)

  // 带进度显示的上传配置
  const uploadHandler = async (file) => {
    setUploading(true)
    try {
      const result = await realUpload(file)
      setUploading(false)
      return result
    } catch (error) {
      setUploading(false)
      return {
        status: 'fail',
        message: error.message
      }
    }
  }

  return (
    <Space direction='vertical'>
      <ImageUploader
        ref={input}
        value={fileList}
        onChange={setFileList}
        upload={uploadHandler}
        
        multiple={false}
        accept='image/*'
        showUpload={false}
        renderItem={(file) => (
          <div key={file.key} style={{ position: 'relative', height: '150px',width: '150px' }}>
            {console.log(file)}
            <img
              src={file.props.url}
              alt="avatar"
              style={{
                width: '100%',
                height: 150,
                objectFit: 'cover',
                borderRadius: 8
              }}
            />
            {uploading && (
              <div style={{
                position: 'absolute',
                bottom: 0,
                left: 0,
                right: 0,
                background: 'rgba(0,0,0,0.5)',
                color: 'white',
                textAlign: 'center',
                padding: 4
              }}>
                上传中...
              </div>
            )}
          </div>
        )}
      />
      <Button onClick={() => {
        console.log(input.current)
        input.current?.nativeElement.click()}}>
        {uploading ? '上传中...' : '选择头像'}
      </Button>
    </Space>
  )
}